<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/2/21
 * Time: 13:44
 */

namespace app\admin\controller;

use app\admin\model\SystemManager as SystemManagerModel;
use app\admin\model\SystemManager;
use app\admin\model\SystemRole;
use app\admin\validate\SystemManagerValidate;
use think\Db;

class Manager extends CheckLogin
{

    public function index()
    {
        if ($this->request->isAjax()) {
            $page = (int)$this->request->post('pageIndex');
            $limit = (int)$this->request->post('pageSize');
            $name = $this->request->post('dataName', '');
            $status = $this->request->post('dataStatus', '');
            $offset = ($page - 1) * $limit;
            $where = ['is_del' => ['=', 0]];
            !empty($name) && $where['username'] = ['like', '%' . $name . '%'];
            !empty($status) && $where['status'] = ['=', $status];
            $managerModel = new SystemManagerModel();
            $totalCount = $managerModel->getCount($where);
            $list = $totalCount > 0 ? $managerModel->getManagersAll($where, $offset, $limit) : [];
            if (!empty($list)) {
                $typesInfo = SystemManagerModel::$statusInfo;
                foreach ($list as $k => $v) {
                    $list[$k]['status'] = $typesInfo[$v['status']];
                }
            }
            $data = [
                'code' => 0,
                'msg' => 'success',
                'list' => $list,
                'count' => $totalCount
            ];
            return $this->json($data);
        } else {
            $this->assign(['status' => SystemManagerModel::$statusInfo]);
            return $this->fetch();
        }
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $managerValidate = new SystemManagerValidate();
            if($managerValidate->scene('add')->check($data)) {
                $managerModel = new SystemManagerModel();
                if($data['typeid']!=16){
                    unset($data['is_default'],$data['send_name'],$data['provice_id'],$data['city_id'],$data['address']);
                    if ($managerModel->add($data)) {
                        return $this->jsonSuccess('添加成功...', ['url' => '/admin/manager/index']);
                    }
                    return $this->jsonFail('添加失败...');
                }else{
                    Db::startTrans();
                    try {
                        $send=[];$send['send_name']=$data['send_name'];
                        $send['provice_id']=$data['provice_id'];
                        $send['city_id']=$data['city_id'];
                        $send['address']=$data['address'];
                        $send['is_default']=$data['is_default'];
                        if( $send['is_default']==1){
                            $allId= Db::table('hui_send')->field('id')->where('is_del=0')->select();
                            $ids=array_column($allId,'id');
                            foreach ($ids as $v){
                                Db::table('hui_send')->update(['is_default'=>0,'id'=>$v]);
                            }
                        }
                        $count=Db::table('hui_send')->where('is_del=0 AND is_default=1')->count();
                        if($count==0&&$send['is_default']==0){
                            return $this->jsonFail('请先添加默认配送站...');
                        }
                        $sendId=Db::table('hui_send')->insertGetId($send);
                        $manager=[];$manager['username']=$data['username'];
                        $manager['real_name']=$data['real_name'];
                        $manager['password']=md5(md5($data['password']));
                        $manager['typeid']=$data['typeid'];
                        $manager['status']=$data['status'];
                        $manager['send_id']=$sendId;
                        Db::table('vote_system_manager')->insert($manager);
                        Db::commit();
                        return $this->jsonSuccess('添加成功...', ['url' => '/manager/index']);
                    }catch(\Exception $e){
                        Db::rollback();
                        return $this->jsonFail('添加失败');
                    }
                }
            }else{
                return $this->jsonFail($managerValidate->getError());
            }
        } else {
            $provice = Db::table('hui_area')->field('id,name')->where('level_count=1')->select();
            $city=Db::table('hui_area')->field('id,name')->where('typeid='.$provice[0]['id'])->select();
            $systemRole = new SystemRole();
            $this->assign([
                'roles' => $systemRole->getAllRoles(),
                'provice' => $provice,'city'=>$city
            ]);
            return $this->fetch();
        }
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $managerValidate = new SystemManagerValidate();
            if($managerValidate->scene('edit')->check($data)) {
                $managerModel = new SystemManagerModel();

                if($data['typeid']!=16){
                    unset($data['is_default'],$data['send_name'],$data['provice_id'],$data['city_id'],$data['address']);
                    $data['send_id']=0;
                    if ($managerModel->edit($data)) {
                        return $this->jsonSuccess('修改成功...', ['url' => '/admin/manager/index']);
                    }
                    return $this->jsonFail('修改失败...');
                }else{
                    Db::startTrans();
                    try {
                        $send=[];$send['send_name']=$data['send_name'];
                        $send['provice_id']=$data['provice_id'];
                        $send['city_id']=$data['city_id'];
                        $send['address']=$data['address'];
                        $send['id']=$data['send_id'];
                        $send['is_default']=$data['is_default'];
                        if( $send['is_default']==1){
                            $allId= Db::table('hui_send')->field('id')->where('is_del=0')->select();
                            $ids=array_column($allId,'id');
                            foreach ($ids as $v){
                                Db::table('hui_send')->update(['is_default'=>0,'id'=>$v]);
                            }
                        }
                        $count=Db::table('hui_send')->where('is_del=0 AND is_default=1')->count();
                        if($count==0&&$send['is_default']==0){
                            return $this->jsonFail('请先添加默认配送站...');
                        }
                        Db::table('hui_send')->update($send);
                        $manager=[];$manager['username']=$data['username'];
                        $manager['real_name']=$data['real_name'];
                        $manager['password']=md5(md5($data['password']));
                        $manager['typeid']=$data['typeid'];
                        $manager['status']=$data['status'];
                        $manager['send_id']=$data['send_id'];
                        $manager['id']=$data['id'];
                        //dump($manager);die;
                        Db::table('hui_system_manager')->update($manager);
                        Db::commit();
                        return $this->jsonSuccess('修改成功...', ['url' => '/admin/manager/index']);
                    }catch(\Exception $e){
                        Db::rollback();
                        //return $this->jsonFail($e->getMessage());
                        return $this->jsonFail('修改失败');
                    }
                }
            }else{
                return $this->jsonFail($managerValidate->getError());
            }
        } else {
            $managerId = $this->request->param('id');

            $manager=SystemManager::get(['id'=>$managerId]);
            $sendId=$manager->send_id;
            if($sendId!=0){
                $send=Db::table('hui_send')->where('id='.$sendId)->find();
                $provice = Db::table('hui_area')->field('id,name')->where('level_count=1')->select();
                $city=Db::table('hui_area')->field('id,name')->where('typeid='.$send['provice_id'])->select();
            }else{
                $send=Db::table('hui_send')->where('id='.$sendId)->find();
                $provice = Db::table('hui_area')->field('id,name')->where('level_count=1')->select();
                $city=Db::table('hui_area')->field('id,name')->where('typeid='.$provice[0]['id'])->select();

            }
            $systemRole = new SystemRole();
            $this->assign([
                'manager' => SystemManager::get(['id'=>$managerId]),
                'roles' => $systemRole->getAllRoles(),
                'send' => $send,'provice' => $provice,'city'=>$city
            ]);
            return $this->fetch();
        }
    }

    public function del()
    {
        $managerId = $this->request->post('id');

        $managerModel = new SystemManagerModel();
        $manager=$managerModel::get($managerId);
        if($manager['send_id']==0){
            if($managerId == 1){
                return $this->jsonFail('该管理员不能被删除');
            }
            if ($managerModel->del($managerId)) {
                return $this->jsonSuccess('删除成功');
            }
            return $this->jsonFail('删除失败');
        }else{
            Db::startTrans();
            try{
                Db::table('hui_system_manager')->update(['id'=>$managerId, 'is_del'=>time()]);
                Db::table('hui_send')->update(['id'=>$manager['send_id'], 'is_del'=>time()]);
                Db::commit();
                return $this->jsonSuccess('删除成功...', ['url' => '/manager/index']);

            }catch(\Exception $e){
                Db::rollback();
                //return $this->jsonFail($e->getMessage());
                return $this->jsonFail('删除失败');
            }
        }

    }


}
